// packageAdvance/pages/advance-index/advance-index.js
import {
    getuserapplyconfigapi,
    postadvanceapplyapi,
    getadvanceapplylistapi
} from '../../api/advance'
import {
    toast,
    wxfileTobase64
} from '../../../utils/util.js'
import dayjs from 'dayjs'
import user from '../../../utils/user'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        totalAmount: '',
        idcard: '',
        base64: [],
        maxprice: 0,
        aimgurl: [],
        advanceprice: null,
        showagreement: false,
        active: 0,
        advance: null,
        remark: null,
        checked: false,
        companyName: '',
        companyId: null,
        advancehistorylist: [],
        oktoadvance: true,
        cgmaxflag: false,
        ygqyarray: [],
        ygqyindex: null,
        infoarr: [],
        popflag: false,
        date: '',
        pageSize: 10,
        pagenum: 1,
        hasnext: true
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.setData({
            date: dayjs().format('YYYY-MM')
        })
        this.getuserapplyconfig()
    },
    getadvanceapplylist() {
        if (this.data.hasnext) {
            getadvanceapplylistapi({
                idCardNo: this.data.idcard,
                queryMonth: this.data.date,
                pageSize: this.data.pageSize,
                pageNum: this.data.pagenum
            }).then((res) => {
                console.log(res)
                res.list.forEach((ele, i) => {
                    ele.payTime = dayjs(ele.payTime).format('YYYY-MM-DD-HH:mm:ss')
                    // 0 ：审核中 1:未通过 2:待领取 3：已领取 4：停止 5：失败 6:进行中
                    if (ele.applyStatus === 0 && ele.auditStatus === null && ele.status === null) {
                        ele.endstatus = 0
                    } else if (ele.applyStatus === 1 && ele.auditStatus === null && ele.status === null) {
                        ele.endstatus = 0
                    } else if (ele.applyStatus === 1 && ele.auditStatus === 0 && ele.status === null) {
                        ele.endstatus = 0
                    } else if (ele.applyStatus === 1 && ele.auditStatus === 0 && ele.status === 0) {
                        ele.endstatus = 0
                    } else if (ele.applyStatus === 1 && ele.auditStatus === 1 && ele.status === 1) {
                        ele.endstatus = 3
                    } else if (ele.applyStatus === 2 && ele.auditStatus === null && ele.status === null) {
                        ele.endstatus = 1
                    } else if (ele.applyStatus === 1 && ele.auditStatus === 1 && ele.status === 0) {
                        ele.endstatus = 2
                    } else if (ele.applyStatus === 1 && ele.auditStatus === 1 && ele.status === 2) {
                        ele.endstatus = 4
                    } else if (ele.applyStatus === 1 && ele.auditStatus === 1 && ele.status === 3) {
                        ele.endstatus = 6
                    } else if (ele.applyStatus === 1 && ele.auditStatus === 1 && ele.status === 4) {
                        ele.endstatus = 5
                    } else if (ele.applyStatus === 1 && ele.auditStatus === 2 && ele.status === null) {
                        ele.endstatus = 1
                    } else if (ele.applyStatus === 1 && ele.auditStatus === 2 && ele.status === 0) {
                        ele.endstatus = 1
                    }
                })
                let arr = this.data.advancehistorylist.concat(res.list)
                this.setData({
                    hasnext: res.hasNextPage,
                    advancehistorylist: arr,
                    totalAmount: res.totalAmount
                })
                console.log(this.data.advancehistorylist)
            })
        } else {
            return
        }
    },
    call(e) {
        if (e.currentTarget.dataset.i) {
            wx.makePhoneCall({
                phoneNumber: e.currentTarget.dataset.i,
            })
        } else {
            wx.showToast({
                icon: 'none',
                title: '暂无驻场手机号',
            })
        }

    },
    getuserapplyconfig() {
        getuserapplyconfigapi().then((res) => {
            console.log(res, 'syufguyf')
            if (!res.companyId) {
                this.setData({
                    oktoadvance: false
                })
                return
            }
            if (!res.companyName) {
                this.setData({
                    oktoadvance: false
                })
                return
            }
            if (!res.serveCompanyList) {
                this.setData({
                    oktoadvance: false
                })
                return
            }
            if (res.serveCompanyList.length === 0) {
                this.setData({
                    oktoadvance: false
                })
                return
            }
            if (!res.id) {
                this.setData({
                    oktoadvance: false
                })
                return
            }
            const arr = res.serveCompanyList.map((ele, i) => {
                return ele.serveCompanyName
            })
            this.setData({
                infoarr: res.serveCompanyList,
                maxprice: res.applyQuota,
                companyId: res.companyId,
                companyName: res.companyName,
                ygqyarray: arr
            })
        })
    },
    postadvanceapply() {
        postadvanceapplyapi({
            companyId: this.data.companyId,
            companyName: this.data.companyName,
            serveCompanyId: this.data.infoarr[this.data.ygqyindex].id,
            advanceAmount: this.data.advanceprice,
            applyRemark: this.data.remark,
            files: this.data.base64
        }).then((res) => {
            console.log(res, 'fdsgytdsgdhirsu')
            if (res === '') {
                this.setData({
                    popflag: true
                })
            }
        })
    },
    todetail(e) {
        console.log(e.currentTarget.dataset.i)
        wx.navigateTo({
            url: '../advance-detail/advance-detail?id=' + e.currentTarget.dataset.i + '&showbottom=0',
        })
    },
    bindDateChange: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            date: e.detail.value,
            pagenum: 1,
            hasnext: true,
            advancehistorylist: []
        })
        this.getadvanceapplylist()
    },

    tojl() {
        console.log(111)
        this.setData({
            active: 1,
            popflag: false,
            pagenum: 1,
            hasnext: true,
            advancehistorylist: []
        })
        this.getadvanceapplylist()
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        user.waitLogin().then((res) => {
            this.setData({
                idcard: user.cardNo,
            })
            this.getadvanceapplylist()
        })
    },
    closepop() {
        this.setData({
            popflag: false
        })
        wx.navigateBack()
    },
    chooseimg() {
        wx.showActionSheet({
            itemList: ['从相册中选择', '拍照'],
            itemColor: '#000000',
            success: (res) => {
                if (!res.cancel) {
                    if (res.tapIndex == 0) {
                        this.chooseWxImage('album')
                    } else if (res.tapIndex == 1) {
                        this.chooseWxImage('camera')
                    }
                }
            }
        })
    },
    chooseWxImage: function (type) {
        wx.chooseImage({
            count: 2,
            sizeType: ['original', 'compressed'],
            sourceType: [type],
            success: async (res) => {
                // 选择图片后的完成确认操作
                this.setData({
                    aimgurl: [],
                    base64: []
                })
                this.data.aimgurl = res.tempFilePaths
                this.setData({
                    aimgurl: this.data.aimgurl
                })
                const tempFilePaths = res.tempFilePaths
                const promiseList = []
                for (const i in tempFilePaths) {
                    promiseList.push(wxfileTobase64(tempFilePaths[i]))
                }
                const result = await Promise.all(promiseList)
                this.data.base64 = result
            }
        })
    },
    changeprice(e) {
        let value = this.validateNumber(e.detail.value) * 1
        console.log(value)
        if (value > this.data.maxprice) {
            this.setData({
                cgmaxflag: true
            })
        } else {
            this.setData({
                cgmaxflag: false
            })
        }
        this.setData({
            advanceprice: value
        })
    },
    bindPickerChange(e) {
        console.log(e)
        this.setData({
            ygqyindex: e.detail.value
        })
    },
    changeremark(e) {
        console.log(e)
        this.setData({
            remark: e.detail.value
        })
    },
    validateNumber(val) {
        if (!val) return 0
        // val = val.replace(/\s*/g, '')
        return val.replace(/\s*/g, '').replace(/\D/g, '')
    },
    changetab(e) {
        console.log(e.currentTarget.dataset.i)
        this.setData({
            active: e.currentTarget.dataset.i
        })
    },
    changestatus() {
        if (this.data.checked == false) {
            this.setData({
                showagreement: true,
            })
        } else {
            this.setData({
                checked: !this.data.checked
            })
        }

    },
    showagreement() {
        this.setData({
            showagreement: true
        })
    },
    gotoadvance() {
        // setTimeout(() => {
        //     this.setData({
        //         popflag: true
        //     })
        // }, 0);

        // return
        if (this.data.remark) {
            this.data.remark = this.data.remark.replace(/\s/g, '')
        }
        if (/\s+/.test(this.data.remark)) {
            toast('备注不可输入多个空格')
            return
        }
        if (/\.\./.test(this.data.remark)) {
            toast('备注不可输入多个.')
            return
        }
        if (!this.data.remark) {
            toast('请输入备注')
            return
        }
        if (this.data.ygqyindex === null) {
            toast('请选择用工企业')
            return
        }
        if (this.data.cgmaxflag) {
            toast('超出公司最大预支金额')
            return
        }
        if (this.data.advanceprice == 0 || this.data.advanceprice === null) {
            toast('请输入预支金额')
            return
        }
        this.postadvanceapply()
        // if (this.data.checked) {
        //     console.log('去预支页面');
        // } else {
        //     this.setData({
        //         showagreement: true
        //     })
        // }
    },
    closeagreement() {
        this.setData({
            showagreement: false,
            checked: false
        })
    },
    okadvance() {
        this.setData({
            showagreement: false,
            checked: true
        })
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        this.setData({
            pagenum: this.data.pagenum + 1
        })
        this.getadvanceapplylist()
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})